import requests
from requests.adapters import HTTPAdapter
requests.packages.urllib3.disable_warnings()


class RequestsService:
    def __init__(self, timeout=10, headers={}):
        """
        :param timeout: 每个请求的超时时间
        """
        session = requests.Session()
        # : 在session实例上挂载Adapter实例, 目的: 请求异常时,自动重试
        session.mount('http://', HTTPAdapter(max_retries=3))
        session.mount('https://', HTTPAdapter(max_retries=3))

        # : 设置为False, 主要是HTTPS时会报错, 为了安全也可以设置为True
        session.verify = False

        # : 公共的请求头设置
        session.headers = headers

        # : 挂载到self上面
        self._session = session
        self.timeout = timeout

    def get(self, url: str, query_dict: dict = {}, headers: dict = {}) -> dict:
        """
        :param url: 请求地址
        :param query_dict: 一般GET的参数都是放在URL查询参数里面
        :return:
        """
        if headers:
            self._session.headers = headers
        response = self._session.get(url, params=query_dict)
        return response

    def post(self, url: str, form_data: dict = None, body_dict: dict = None, headers: dict = {}) -> dict:
        """POST

        :param url: 请求地址
        :param form_data: 有时候POST的参数是放在表单参数中
        :param body_dict: 有时候POST的参数是放在请求体中(这时候 Content-Type: application/json )
        :return:
        """
        if headers:
            self._session.headers = headers
        if form_data:
            response = self._session.post(url, data=form_data, timeout=self.timeout, verify=False)
        if body_dict:
            response = self._session.post(url, json=body_dict, timeout=self.timeout, verify=False)

        if not form_data and not body_dict:
            response = self._session.post(url, timeout=self.timeout, verify=False)

        return response

    def __del__(self):
        """当实例被销毁时,释放掉session所持有的连接

        :return:
        """
        if self._session:
            self._session.close()
